package com.zxl.grocery.microservice.admin.rest;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zxl.grocery.microservice.admin.entity.TestUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: zxl
 * @Description:
 * @Date: Created in 23:46 2017/10/16
 * @Modified By:
 */
@RestController
public class Test {

    @Autowired
    private EurekaClient eurekaClient;

    @Autowired
    private DiscoveryClient discoveryClient;
    /**
     * @Author: Lzx
     * @Description: 从Eureka服务器发现服务实例
     * 返回ip地址和端口号 例如：http://192.168.31.1:8762/
     * @Params:  * @param null
     * @Date: 23:48 2017/10/16
     */
    @GetMapping("/eureka-instance")
    public String serviceUrl() {
        InstanceInfo instance = eurekaClient.getNextServerFromEureka("GROCERY-ADMIN", false);
        return instance.getHomePageUrl();
    }

    /**
     * @Author: Lzx
     * @Description: 本地服务实例的信息
     * 返回：{"host":"192.168.31.1","port":8762,"metadata":{},"uri":"http://192.168.31.1:8762","secure":false,"serviceId":"grocery-admin"}
     * "secure":false是否使用https
     * @Params:  * @param null
     * @Date: 23:46 2017/10/16
     */
    @GetMapping("/instance-info")
    public ServiceInstance showInfo(){
        ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();
        return localServiceInstance;
    }

    /**
     * @Author: Lzx
     * @Description: 测试Hystrix
     * @Params:  * @param null
     * @Date: 23:48 2017/10/26
     */
    @GetMapping("/test/{id}")
    @HystrixCommand(fallbackMethod = "findByIdFallback")
    public TestUser findById(@PathVariable Integer id){
        //todo 调用其他服务接口
        TestUser testUser = new TestUser();
        testUser.setId(id);
        testUser.setName("normal");
        testUser.setUsername("test1");
        testUser.setPassword("123456");
        return testUser;
    }
    public TestUser findByIdFallback(Integer id){
        TestUser testUser = new TestUser();
        testUser.setId(0);
        testUser.setName("fallback");
        testUser.setUsername("test2");
        testUser.setPassword("123456");
        return testUser;
    }
}
